package slave

import (
	"backend/internal/common/errorx"
	"context"
	"net/http"
	"time"

	"backend/internal/svc"
	"backend/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ReadRegisterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewReadRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ReadRegisterLogic {
	return &ReadRegisterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ReadRegisterLogic) ReadRegister(req *types.SlaveAddress) (resp *types.RegisterValueResponse, err error) {
	resp = &types.RegisterValueResponse{Data: []types.RegisterValue{}}
	client := l.svcCtx.ClientManager.GetClient(req.DeviceName)
	if client == nil {
		return nil, errorx.NewCodeError(http.StatusNotFound, "无法找到该设备")
	}
	// 读取寄存器
	values, err := client.ReadRegister(uint8(req.SlaveId), req.RegisterType, uint16(req.StartAddress), uint16(req.EndAddress))
	if err != nil {
		return nil, err
	}
	resp.Status = http.StatusOK
	resp.Msg = "读取寄存器成功"

	currentTime := time.Now().Format("2006-01-02 15:04:05")
	for i := req.StartAddress; i <= req.EndAddress; i++ {
		// 调整索引计算
		index := i - req.StartAddress
		resp.Data = append(resp.Data, types.RegisterValue{
			Address: i,
			Value:   values[index],
			Time:    currentTime,
			Status:  true,
		})
	}
	return resp, nil
}
